package com.example.provider2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

// 客户端 MainActivity.java
public class MainActivity extends AppCompatActivity {
    // Authority 必须与服务端完全一致
    private static final String AUTHORITY = "com.example.provider.MyProvider";
    private static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 在 onCreate 中调用
        callProvider1();  // 已有权限，直接调用
        findViewById(R.id.button).setOnClickListener(view -> showCompatibleDialog());

    }
    private void showCompatibleDialog() {
        RemoteViews remoteViews = fetchRemoteViews(this);

        if (remoteViews == null) return;

        // 创建使用系统主题的 Context
        Context context = new ContextThemeWrapper(this, R.style.Theme_Provider2);

        Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        // 创建简单布局
        LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        layout.setPadding(32, 32, 32, 32);

        try {
            // 尝试应用 RemoteViews
            View remoteView = remoteViews.apply(context, layout);
            layout.addView(remoteView);
        } catch (Exception e) {
            // 创建回退视图
            e.printStackTrace();
            TextView errorView = new TextView(context);
            errorView.setText("内容加载失败");
            layout.addView(errorView);
        }
        dialog.setContentView(layout);
        // 显示配置
        Window window = dialog.getWindow();
        if (window != null) {
            window.setLayout(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT
            );
        }
        dialog.show();
    }

    private RemoteViews fetchRemoteViews(Context context) {
        try {
            Bundle result = context.getContentResolver().call(
                    CONTENT_URI,
                    "onClick",  // 方法名必须与服务端匹配
                    null,
                    null
            );
            return (result != null) ? result.getParcelable("remote_views") : null;
        } catch (Exception e) {
            Log.e("RemoteView", "获取失败", e);
            return null;
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (requestCode == 100 && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            callProvider1();
        } else {
            Toast.makeText(this, "Permission denied!", Toast.LENGTH_SHORT).show();
        }
    }

    // 封装调用 Provider 的逻辑
    private void callProvider1() {
        //1.可以调用call()方法
        Log.d("ProviderDebug", "Attempting to access URI: " + CONTENT_URI);
        Bundle response = getContentResolver().call(
                CONTENT_URI,
                "getData",  // 方法名必须与服务端匹配
                null,
                null
        );
        String message = response.getString("response");
        ((TextView) findViewById(R.id.text)).setText(message);

        //2.可以调用metaData标签中的数据
        // 通过 PackageManager 获取 ProviderInfo
        ProviderInfo providerInfo = getPackageManager().resolveContentProvider(
                AUTHORITY, // 对应 Provider 的 authorities
                PackageManager.GET_META_DATA
        );

        if (providerInfo != null && providerInfo.metaData != null) {
            // 读取 meta-data
            String value = providerInfo.metaData.getString("custom_key");
            Log.d("MetaData", "Value: " + value); // 输出: custom_value
            ((TextView) findViewById(R.id.text2)).setText(value);
        }
    }
}